package top.riske.imagebed.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.riske.imagebed.entity.CFile;
import top.riske.imagebed.exception.FileHadExistException;
import top.riske.imagebed.exception.FileHashDifferentException;
import top.riske.imagebed.service.FileUploadService;
import top.riske.imagebed.utils.ImageUtils;
import top.riske.imagebed.utils.Result;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * created by vital on 2025/3/5 上午8:40
 */
@RestController
public class FileUploadController {

    @Resource
    private FileUploadService fileUploadService;

    @Value("${imageBed.server.url}")
    private String imageBedPath;

    /**
     * 预上传文件，检查文件是否已经存在，存在则直接返回文件链接
     * @param fileHash 文件md5值
     * @return
     */
    @GetMapping("/file/prepare")
    public Result<String> prepareUpload(String fileHash, HttpServletRequest request) {
        if(fileHash == null || fileHash.length() != 32){
            return Result.fail("文件md5值错误");
        }
        return fileUploadService.prepareUpload(fileHash, request);
    }

    /**
     * 上传文件
     * @param file 文件
     * @param fileHash 文件md5值
     * @return
     */
    @PostMapping("/file/upload")
    public Result<String> upload(MultipartFile file, String fileHash, HttpServletRequest request) {
        if(file == null){
            return Result.fail("未接收到文件");
        }

        try {
            // 校验hash
            String hash = fileUploadService.checkHash(file, fileHash);
            fileHash = hash;
            // 保存文件
            Result<CFile> res = fileUploadService.saveFile(file, fileHash,request);
            // 获取文件完整url
            String url = imageBedPath + res.getData().getPath();
            System.out.println("文件URL:"+ url);
            if(res.isSuccess()){
                return Result.success(url);
            }else{
                return Result.fail(res.getMessage());
            }
        } catch (IOException e) {
            return Result.fail("文件保存错误");
        } catch (NoSuchAlgorithmException e) {
            return Result.fail("文件校验算法错误");
        } catch (FileHashDifferentException e) {
            return Result.fail("文件校验错误");
        } catch (FileHadExistException e) {
            return Result.success(e.getData());
        }
    }


}
